package com.mall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.mall.common.constant.AuthConstant;
import com.mall.common.enums.ResponseEnum;
import com.mall.common.exception.BizException;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author wuyijie
 * @className: AuthFilter
 * @description: TODO
 * @date 2021/6/13 15:59
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StrUtil.isEmpty(token)) {
            return chain.filter(exchange);
        }
        try {
            //从token中解析用户信息并设置到Header中去
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();

            log.info("AuthGlobalFilter.filter() user:{}", userStr);

            ServerHttpRequest request = exchange.getRequest().mutate().header("user", userStr).build();
            exchange = exchange.mutate().request(request).build();
        } catch (java.text.ParseException e) {
            e.printStackTrace();
            throw new BizException(ResponseEnum.USER_PARSE_ERROR);
        }
        return chain.filter(exchange);
    }

    /**
     * TODO: 返回过滤器执行顺序。数值越小，优先级越高。
     *
     * @return int
     * @author wuyijie
     * @date 2021/6/13 16:00
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
